package com.sptpc.hello.service.impl;

import com.sptpc.hello.modei.Category;
import com.sptpc.hello.modei.Drink;
import com.sptpc.hello.repository.CategoryRepository;
import com.sptpc.hello.repository.DrinkRepository;
import com.sptpc.hello.service.IDrinkService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DrinkjpaService implements IDrinkService {
    @Autowired
    private DrinkRepository drinkRepository;

    @Autowired
    private CategoryRepository categoryRepositor;

    @Override
    public List<Drink> getAllDriks(){
        return drinkRepository.findAll();
    }

    @Override
    public void addNewDrink(Drink drink, Integer categoryId) {
        //通过categoryId查询category
        Category category = categoryRepositor.findById(categoryId).orElse(null);
        //将category设置给drink
        drink.setCategory(category);

        drinkRepository.save(drink);
    }

    @Override
    public Drink getDrinkById(Integer id) {
//        Optional<Drink> optional = drinkRepository.findById(id);
//        if (optional.isPresent()){
//            return optional.get();
//        }
        return drinkRepository.findById(id).orElse(null);
    }

    @Override
    public void updateDrink(Drink drink) {
        drinkRepository.save(drink);
    }

    @Override
    public void deleteDrinkById(Integer id) {
        drinkRepository.deleteById(id);

    }
}
